package org.example.controller;

import org.example.entity.Comments;
import org.example.models.R;
import org.example.service.CommentsService;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/comments")
public class CommentsController {
    @Autowired
    private CommentsService commentsService;
    @Autowired
    private UserService userService;

    @GetMapping("/findUserById") //根据评论id查询用户
    private R<List<Comments>> findUserById(@RequestParam("commentId") Integer commentId) {
        List<Comments> selectTheUserForTheCommentId = commentsService.selectTheUserForTheCommentId(commentId);
        return R.success( selectTheUserForTheCommentId);
    }

    @GetMapping("/queryCommentsWithTheBoundID")//根据绑定的ID查询评论
    private R<List<Comments>> queryCommentsWithTheBoundID(@RequestParam("boundId") String boundId) {
        List<Comments> comments = commentsService.selectUserByCommentId(boundId);//根据绑定的ID查询评论
        if (comments.size() == 0) {//评论为空
            return R.error(null);//返回错误信息
        }
        return R.success(comments);//返回评论
    }

    //根据用户id添加评论
    @PostMapping("/insert")
    private R<String> insert(@RequestBody Comments comments) {
        comments.setCreatedAt(new Date());
        comments.setCommentandlike(0);
        boolean save = commentsService.save(comments);
        if (save) {
            return R.success("评论成功");
        } else {
            return R.error("评论失败");
        }
    }

    //根据id修改点赞数
    @PostMapping("/updateCommentAndLikeById")
    private R<String> updateCommentAndLikeById(@RequestBody Comments comments) {
        Comments byId = commentsService.getById(comments.getCommentId());
        byId.setCommentandlike(byId.getCommentandlike() + 1);
        boolean b = commentsService.updateById(byId);
        if (b) {
            return R.success("200");
        } else {
            return R.error("400");
        }
    }
    //根据id修改点赞数
    @PostMapping("/updateCommentAndLikeByIdj")
    private R<String> updateCommentAndLikeByIdj(@RequestBody Comments comments) {
        Comments byId = commentsService.getById(comments.getCommentId());
        int i = byId.getCommentandlike() - 1;
        System.out.println(i);
        byId.setCommentandlike(i);
        boolean b = commentsService.updateById(byId);
        if (b) {
            return R.success("200");
        } else {
            return R.error("400");
        }
    }
}
